/**
 * Created by bianbian3 on 2018/8/17.
 */

import React, { Component, PropTypes } from 'react';
import {
	Alert, Dimensions, StyleSheet, Text, View, ScrollView, TouchableOpacity, Platform,
} from 'react-native';
import { MtContainer, MtChar, MtEdit, MtFixedButton, MtLabelBar, MtToast, MtPopupPicker,MtNavBar,
	MtSeparator, MtDateTimePicker, MtColor, MtActionButton, MtListView, MtEmptyView } from 'martian-ui';
const DeviceCell = require('../components/DeviceCell');
import {fetchDeviceList} from '../action/girlAction';

import dismissKeyboard from 'react-native/Libraries/Utilities/dismissKeyboard';
const { MtM3, MtL3, MtW1, MtLabel } = MtChar;
import TipBar from '../components/TipBar';
import values from 'lodash/values';
import keys from 'lodash/keys';
import {connect} from 'react-redux';
const EntityLabels = require('../constants/entities');
import assign from 'lodash/assign';
import NavigationBar from '../components/common/NavigationBar'

function removeA(arr) {
	var what, a = arguments, L = a.length, ax;
	while (L > 1 && arr.length) {
		what = a[--L];

		while ((ax= arr.indexOf(what)) !== -1 || (ax= arr.indexOf(what.toString())) !== -1) {
			arr.splice(ax, 1);
		}
	}
	return arr;
}

function _renderNotAddDevice(deviceId) {
	const { navigator, addfun, oldDeviceIds } = this.props;
	const { addedDeviceIds, newDeviceIds } = this.state;
	return (
		<DeviceCell
			navigator={navigator}
			deviceId={deviceId}
			addDeviceId={
				(deviceId)=>{
					let  new1 = [];
					new1 = addedDeviceIds && addedDeviceIds.concat(deviceId);

					let  new2 = [];
					new2 =removeA(newDeviceIds, deviceId);

					this.setState({addedDeviceIds: new1 })
					this.setState({newDeviceIds: new2 })
					addfun(new1)
				}
			}
			rightShowType={2}
		/>
	);
}
function quchongConcat(arr1,arr2){
	//不要直接使用var arr = arr1，这样arr只是arr1的一个引用，两者的修改会互相影响
	var arr = arr1.concat();
	//或者使用slice()复制，var arr = arr1.slice(0)
	for(var i=0;i<arr2.length;i++){
		arr.indexOf(arr2[i]) === -1 ? arr.push(arr2[i]) : 0;
	}
	return arr;
}
function uniq(array){
	var temp = []; //一个新的临时数组
	for(var i = 0; i < array.length; i++){
		if(temp.indexOf(array[i]) == -1 && temp.indexOf(array[i].toString()) == -1 ){
			temp.push(array[i]);
		}
	}
	return temp;
}

function _renderAddedDevice(deviceId) {
	const { navigator, addfun, oldDeviceIds } = this.props;
	const { addedDeviceIds, newDeviceIds } = this.state;
	return (
		<DeviceCell
			navigator={navigator}
			deviceId={deviceId}
			removeDeviceId={
				(deviceId)=>{
					let  new1 = [];
					new1 = newDeviceIds && newDeviceIds.concat(deviceId);
					let new2 = [];
					new2 =removeA(addedDeviceIds, deviceId);
					this.setState({addedDeviceIds: new2 })
					this.setState({newDeviceIds: new1 })
					addfun(new2)

				}
			}
			rightShowType={3}
		/>
	);
}

class ManageActionDevice extends Component {
	constructor(props) {
		super(props)
		// 初始状态
		this.state = {
			addedDeviceIds : [],
			// newDeviceIds : [],

		}

	}

	convertPropsToStates(props) {
		const { devicesEntities, oldDeviceIds} = props;
		const {addedDeviceIds} = this.state;

		let newDeviceIds =[];
		if (devicesEntities && keys(devicesEntities).length > 0) {
			newDeviceIds = values(devicesEntities).map(ele => ele.deviceId);
		}

		if (oldDeviceIds && oldDeviceIds.length > 0){
			this.setState({ addedDeviceIds: quchongConcat(oldDeviceIds || [], addedDeviceIds) })
		}

		const newState = assign({

			newDeviceIds,

		});

		if (newState) {
			this.setState(newState);
		}
	}

	componentWillReceiveProps(nextProps) {
		this.convertPropsToStates((nextProps));
	}
	componentWillMount() {
		this.convertPropsToStates(this.props);
	}


	render() {
		const { oldDeviceIds, navigator } = this.props;
		const { newDeviceIds, addedDeviceIds } = this.state;
		//房间场景
		const renderNotAddDevice = _renderNotAddDevice.bind(this);
		const renderAddedDevice = _renderAddedDevice.bind(this);
		let V;
		let V1;
		if (newDeviceIds && newDeviceIds.length > 0) {
			V = (
				<MtListView
					data={newDeviceIds}
					renderRow={renderNotAddDevice}
					initialListSize={10}
					scrollRenderAheadDistance={500}
					onEndReachedThreshold={10}
					renderSeparator={undefined}
					enableEmptySections={true}
					removeClippedSubviews={false}
					onRefresh={() => {
						//  this.refresh();
					}}
					onEndReached={() => {

					}}
				/>
			);
		}
		else {
			V = (
				<MtEmptyView
					onRefresh={() => {
					}}
					desc="您没有设备"
				/>
			);
		}


		if (addedDeviceIds && addedDeviceIds.length > 0 ) {
			V1 = (
				<MtListView
					data={uniq(addedDeviceIds)}
					renderRow={renderAddedDevice}
					initialListSize={10}
					scrollRenderAheadDistance={500}
					onEndReachedThreshold={10}
					renderSeparator={undefined}
					enableEmptySections={true}

					removeClippedSubviews={false}
					onRefresh={() => {
						//  this.refresh();
					}}
					onEndReached={() => {

					}}
				/>
			);
		}
		else {
			V1 = (
				<MtEmptyView
					onRefresh={() => {
					}}
					desc="您没有已经添加设备"
				/>
			);
		}

		return (
			<MtContainer>
        <NavigationBar
          title={'管理执行设备'}
          statusBar={{backgroundColor: '#F4F4F4', barStyle: 'dark-content'}}
          style={{backgroundColor: '#F4F4F4'}}
          navigator={navigator}
        />
				<View style={{ flex: 1}}>
				<View style={{flex: 1}}>
				<MtLabel style={styles.subtitle}>未添加设备</MtLabel>
				{V}
				</View>
				<View style={{flex: 1}}>
				<MtLabel style={styles.subtitle}>已添加设备</MtLabel>
				{V1}
				</View>
				</View>
			</MtContainer>

		);
	}}




function mappingStateToProps(state, ownProps) {

	const entities= state['entities'];
	const devicesEntities = entities[EntityLabels.devices];


	return {
		devicesEntities
	}
}


module.exports = connect(mappingStateToProps)(ManageActionDevice);

const styles = StyleSheet.create({
	textRight: {
		textAlign: 'right',
	},
	subtitle:{
		fontWeight: 'bold',
		alignItems:'center', // 必须设置,否则换行不起作用
		paddingVertical: 40,
		paddingLeft: 20,
		backgroundColor:'#fff'
	},
	manageDeviceTitleStyle:{
		textAlign: 'right',
		fontWeight:'bold',
		fontSize:16,
		color:'#000',
	},
	textRightColor: {
		textAlign: 'right',
		color: MtColor.main,
	},
	listViewStyle:{
		// 改变主轴的方向
		flexDirection:'row',
		// 多行显示
		flexWrap:'wrap',
		// 侧轴方向
		alignItems:'center', // 必须设置,否则换行不起作用
	}
});
